package com.lindroy.jetpacknotes.paging.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ProgressBar
import androidx.core.view.isVisible
import androidx.paging.LoadState
import androidx.paging.LoadStateAdapter
import androidx.recyclerview.widget.RecyclerView
import com.lindroy.jetpacknotes.R

/**
 * @author Lin
 * @date 2022/1/17
 * @function
 */
class FootAdapter : LoadStateAdapter<FootAdapter.ViewHolder>() {

    private var listener: (() -> Unit)? = null

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val btnRetry = itemView.findViewById<Button>(R.id.btnRetry)
        val progressBar = itemView.findViewById<ProgressBar>(R.id.progressBar)
    }

    override fun onBindViewHolder(holder: ViewHolder, loadState: LoadState) {
        holder.progressBar.isVisible = loadState is LoadState.Loading
        holder.btnRetry.isVisible = loadState is LoadState.Error
        holder.btnRetry.setOnClickListener {
            listener?.invoke()
        }

    }

    override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): ViewHolder =
        ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_footer, parent, false))

    fun setOnRetryClickListener(listener: () -> Unit) {
        this.listener = listener
    }
}